package com.huawei.testcloud.location;

import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static final double EARTH_RADIUS = 6378137.0;
    private Button btnStartLocate;
    private Button btnEndLocate;
    private Button btnSgin;
    private TextView tvStartData;
    private TextView tvEndData;
    private TextView tvSign;
    private TextView tvDeviceId;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private RadioGroup rgLocationMode;
    private int position;
    private double startLongitude;
    private double startLatitude;
    private double endLongitude;
    private double endLatitude;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initLocation();
    }

    private void initView(){
        //startService(new Intent(this,MyService.class));
        btnStartLocate= (Button) findViewById(R.id.btn_start_locate);
        btnEndLocate= (Button) findViewById(R.id.btn_end_locate);
        btnSgin= (Button) findViewById(R.id.btn_sign);
        tvStartData= (TextView) findViewById(R.id.tv_start_data);
        tvEndData= (TextView) findViewById(R.id.tv_end_data);
        tvSign= (TextView) findViewById(R.id.tv_sign);
        tvDeviceId= (TextView) findViewById(R.id.tv_device_id);
        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();
        tvDeviceId.setText(szImei);
//        rgLocationMode= (RadioGroup) findViewById(R.id.rg_locationMode);
//        rgLocationMode.setOnCheckedChangeListener(this);
        btnStartLocate.setOnClickListener(this);
        btnEndLocate.setOnClickListener(this);
        btnSgin.setOnClickListener(this);
        UsbManager usbManager=(UsbManager) getSystemService(this.USB_SERVICE);
    }

    /**
     * 初始化定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void initLocation(){
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }



    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0){
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    if(position==0){
                        startLongitude=location.getLongitude();
                        startLatitude=location.getLatitude();
                        tvStartData.setText("经度:"+location.getLongitude()+" 纬度:"+location.getLatitude()+"精度:"+location.getAccuracy()+"米");
                    }else {
                        endLongitude=location.getLongitude();
                        endLatitude=location.getLatitude();
                        tvEndData.setText("经度:"+location.getLongitude()+" 纬度:"+location.getLatitude()+"精度:"+location.getAccuracy()+"米");
                    }
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                    Toast.makeText(MainActivity.this,"定位成功",Toast.LENGTH_SHORT).show();
                    stopLocation();
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                    Toast.makeText(MainActivity.this,"定位失败",Toast.LENGTH_SHORT).show();
                    stopLocation();
                }
                //定位之后的回调时间
                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                Log.i("result","result="+result);
            } else {
                Toast.makeText(MainActivity.this,"定位失败",Toast.LENGTH_SHORT).show();
            }
        }
    };

//    @Override
//    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        if (null == locationOption) {
//            locationOption = new AMapLocationClientOption();
//        }
//        switch (checkedId) {
//            case R.id.rb_batterySaving :
//                locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
//                break;
//            case R.id.rb_deviceSensors :
//                locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
//                break;
//            case R.id.rb_hightAccuracy :
//                locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//                break;
//            default :
//                break;
//        }
//    }

    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void startLocation(){
        //根据控件的选择，重新设置定位参数
        //resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void destroyLocation(){
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    private void isSuccess(){
        if(startLongitude!=0){
            double distance=getDistance(startLongitude,startLatitude,endLongitude,endLatitude);
            Log.i("distance","distance="+distance);
            tvSign.setText("据初始距离:"+distance+"米");
            if(distance<=100){
                Toast.makeText(MainActivity.this,"签到成功",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(MainActivity.this,"您已走出规定范围，不能签到",Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(MainActivity.this,"请先定位",Toast.LENGTH_SHORT).show();
        }
    }

    // 返回单位是米
    private double getDistance(double longitude1, double latitude1,
                                         double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
        + Math.cos(Lat1) * Math.cos(Lat2)
        * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
        }
    private double rad(double d) {
        return d * Math.PI / 180.0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_start_locate:
//                position=0;
//                startLocation();
                startActivity(new Intent(MainActivity.this,SIMActivity.class));
                break;
            case R.id.btn_end_locate:
                position=1;
                startLocation();
                //reBoot();
                break;
            case R.id.btn_sign:
                isSuccess();
                break;
        }
    }

    private void shutDown(){
        try {
            Runtime.getRuntime().exec("su -c \"/system/bin/shutdown\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void reBoot(){
        try {
            Runtime.getRuntime().exec("su -c \"/system/bin/reboot\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
